package com.acme.javaschool.sems.ionio.serialization.net;

import com.acme.javaschool.sems.ionio.serialization.SensorData;
import com.acme.javaschool.sems.ionio.serialization.Serializer;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

import static java.lang.Thread.sleep;

public class SerializationClient {

    private final Serializer<SensorData> serializer;

    public SerializationClient(Serializer<SensorData> serializer) {
        this.serializer = serializer;
    }

    public void work(String host, int port, int objectsNum) {
        try (Socket socket = new Socket(host, port);
             DataInputStream in = new DataInputStream(socket.getInputStream());
             DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
        ) {
            SensorData[] objectsToBeSent = new SensorData[objectsNum];
            for (int i = 0; i < objectsNum; i++) {
                objectsToBeSent[i] = SensorData.generate();
            }

            System.out.println("[client] Gonna send " + objectsNum + " objects.");
            out.writeInt(objectsNum);
            long startMillis = System.currentTimeMillis();
            for (int i = 0; i < objectsNum; i++) {
                if (host.equals("localhost")) { magic(); }

                serializer.serialize(out, objectsToBeSent[i]);
                out.flush();
            }
            int receivedByServerNum = in.readInt();
            System.out.println("[client] Server received " + receivedByServerNum + " objects in " + (System.currentTimeMillis() - startMillis) + " millis.");

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void magic() {
        try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }
    }

}